package com.yao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;

import com.yao.entity.Apple;

/**
 * 第三章 - Lambda 表达式
 * 
 * @author yaoym
 * @date 2018年1月30日 下午3:18:08
 * @version V1.0
 */
public class SessionThird {

	public static void main(String[] args) {
		ref();
	}

	/* 3.6方法引用 */
	public static void ref() {
		// 排序
		sort(Arrays.asList("a", "B", "c", "A"));
		println("");

		// 字符串转整型
		strToInt("4678");
		println("");

		// 批量创建苹果对象
		List<Apple> apples = map(Arrays.asList(100, 4, 58, 98, 22), Apple::new);
		println(apples);
		println("");

		apples = map(Arrays.asList("red","green"), Arrays.asList(100,4,28), Apple::new);
		println(apples);
		println("");
		
		Map<String, Function<Integer, Apple>> map = new HashMap<>();
		map.put("yellow", Apple::new);
		map.put("green", Apple::new);
		
		Apple apple = map("green", 100, map);
		println(apple);
		
	}
	
	public static Apple map(String color, Integer weight, Map<String, Function<Integer, Apple>> map){
		return map.get(color.toLowerCase()).apply(weight);
	}

	/* 具有两个参数的构造函数 */
	public static List<Apple> map(List<String> listc, List<Integer> listw, BiFunction<String, Integer, Apple> f) {
		List<Apple> result = new ArrayList<>();

		for (Integer i : listw) {
			for(String s : listc){

				result.add(f.apply(s, i));
			}
		}

		return result;
	}
	
	/* 具有一个参数的构造函数 */
	public static List<Apple> map(List<Integer> list, Function<Integer, Apple> f) {
		List<Apple> result = new ArrayList<>();

		for (Integer i : list) {
			result.add(f.apply(i));
		}

		return result;
	}

	/* 排序 */
	public static void sort(List<String> inventory) {
		// Lambda排序
		inventory.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
		println("Lamdba排序：");
		println(inventory);

		// 方法引用
		inventory.sort(String::compareToIgnoreCase);
		println("方法引用排序：");
		println(inventory);
	}

	/* 转换字符串 */
	public static void strToInt(String s) {
		// Lambda转换
		Function<String, Integer> f = (String a) -> Integer.parseInt(a);
		Integer result = f.apply(s);
		println("Lambda转换字符串：");
		println(result);

		f = Integer::parseInt;
		result = f.apply(s);
		println("方法引用转换字符串：");
		println(result);
	}

	private static void println(Object o) {
		if (o == null)
			return;

		if (o instanceof Collection<?>) {
			((Collection<?>) o).forEach(System.out::println);
		} else {
			System.out.println(o.toString());
		}
	}

}
